package com.stox.ui.javafx.navigator.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.stox.client.ExchangeClient;
import com.stox.client.ScripClient;
import com.stox.dto.AbstractModel;
import com.stox.dto.Exchange;
import com.stox.ui.javafx.core.util.ExceptionHandler.ExceptionHandlingRunnable;
import com.stox.ui.javafx.core.widget.AbstractModelTreeItem;

@Component("countryTreeItem")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CountryTreeItem extends AbstractModelTreeItem{
	private static final Logger logger = LoggerFactory.getLogger(CountryTreeItem.class);
	
	@Autowired
	private ScripClient scripClient;
	
	@Autowired
	private ExchangeClient exchangeClient;
	
	@Autowired
	private ApplicationContext applicationContext;
	
	private List<Exchange> exchanges;
	
	@Override
	public ObservableList<TreeItem<AbstractModel>> getChildren() {
		loadExchanges();
		return super.getChildren();
	}
	
	@Override
	public boolean isLeaf() {
		return false;
	}
	
	private synchronized void loadExchanges() {
		if(null != getValue() && (null == exchanges || exchanges.isEmpty())) {
			
			new Thread( new ExceptionHandlingRunnable(){
				@Override
				public void doRun() {
					logger.debug("Loading exchanges for country  : "+getValue().getId());
					exchanges = exchangeClient.findByCountryCode(getValue().getId());
					Collections.sort(exchanges);
					List<ExchangeTreeItem> exchangeTreeItems = new ArrayList<ExchangeTreeItem>(exchanges.size());
					for(Exchange exchange : exchanges) {
						ExchangeTreeItem exchangeTreeItem = applicationContext.getBean(ExchangeTreeItem.class);
						exchangeTreeItem.setValue(exchange);
						exchangeTreeItems.add(exchangeTreeItem);
					}
					CountryTreeItem.super.getChildren().setAll(exchangeTreeItems);
				}
			}).start();
		}
	}
	
}
